package cn.yangtianxia.basic.service.Impl;

import cn.yangtianxia.basic.constant.BaseConstants;
import cn.yangtianxia.basic.dto.LoginDto;
import cn.yangtianxia.basic.dto.wechatBinderDto;
import cn.yangtianxia.basic.dto.wechatDto;
import cn.yangtianxia.basic.exception.BusinessException;
import cn.yangtianxia.basic.jwt.JwtUtils;
import cn.yangtianxia.basic.jwt.RsaUtils;
import cn.yangtianxia.basic.jwt.UserInfo;
import cn.yangtianxia.basic.service.ILoginService;
import cn.yangtianxia.basic.util.*;
import cn.yangtianxia.system.domain.Menu;
import cn.yangtianxia.system.mapper.MenuMapper;
import cn.yangtianxia.system.mapper.PermissionMapper;
import cn.yangtianxia.user.domain.Logininfo;
import cn.yangtianxia.user.domain.User;
import cn.yangtianxia.user.domain.Wxuser;
import cn.yangtianxia.user.mapper.LogininfoMapper;
import cn.yangtianxia.user.mapper.UserMapper;
import cn.yangtianxia.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.*;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Value("${jwt.rsa.pri}")
    private String jwtRsaPrivate;//私钥的文件名字

    @Override
    public Map<String, Object>  account(LoginDto dto) {
        //非空判断
        if (StringUtils.isEmpty(dto.getUsername())
        || StringUtils.isEmpty(dto.getPassword())
        || StringUtils.isEmpty(dto.getType())
        ){
            throw new BusinessException("参数不能为空");
        }
        //查询数据库
        Logininfo logininfo = logininfoMapper.loadUsernameAndType(dto.getUsername(),dto.getType());
        if (logininfo == null){
            throw new BusinessException("用户不存在");
        }
        String salt = logininfo.getSalt();
        String md5password = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        //密码判断
        if (!md5password.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误请重新登录");
        }
        //jwt方式存储
        //登录成功之后的业务处理
        return loginSuccessHandler(logininfo);


       /* String token = UUID.randomUUID().toString();
        //保存redis key：token，value:logininfo
        redisTemplate.opsForValue().set(
                token,
                logininfo,
                30,
                TimeUnit.MINUTES
                );
        //不向前端展示盐值和密码，避免暴力破解
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("logininfo", logininfo);
        return map;*/
    }

    /**
     * 登录成功返回数据
     * @param logininfo
     * @return
     */
    private Map<String, Object> loginSuccessHandler(Logininfo logininfo) {
        //创建一个userinfo对象
        UserInfo userInfo = new UserInfo();        //判断是否为员工
        if(logininfo.getType() == 1){//为用户，没有设置菜单按钮权限
            //返回数据
            userInfo.setUser(logininfo);
            userInfo.setMenus(null);//没有返回null
            userInfo.setPermissions(null);//没有返回null
        } else {//员工，设置菜单和按钮
            userInfo.setUser(logininfo);
            List<String> permissions = permissionMapper.loadOwnPermissionByLoginInfoId(logininfo.getId());//获取按钮权限
            List<Menu> menus = menuMapper.loadOwnMenuByLoginInfoId(logininfo.getId());//获取菜单权限
            userInfo.setMenus(menus);
            userInfo.setPermissions(permissions);
        }
        //使用jwt加密
        try {
            //获取私钥
            PrivateKey privateKey = RsaUtils
                    .getPrivateKey(FileCopyUtils
                            .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream(jwtRsaPrivate)));
            //使用秘钥将userinfo加密,生成token,是jwt加密串
            String token = JwtUtils.generateTokenExpireInMinutes(userInfo, privateKey, 30);
            //把数据处理过后返回给前端，和redis的时候一样的做发
            Map<String, Object> map = new HashMap<>();
            logininfo.setSalt(null);//防止被解密
            logininfo.setPassword(null);//防止被解密
            map.put("token",token);
            map.put("logininfo",logininfo);
            map.put("permissions",userInfo.getPermissions());
            map.put("menus",userInfo.getMenus());
            return map;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 扫码，在callback发送请求获取openid和token
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(wechatDto dto) {
        //GET_ACK_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        String binderUrl = dto.getBinderUrl();
        String code = dto.getCode();
        String getTokenUrl = BaseConstants.WechatConstants. TOKEN_URL.
                replace("APPID", BaseConstants.WechatConstants.APPID).
                replace("SECRET", BaseConstants.WechatConstants.SECRET).
                replace("CODE", code);
        String jsonStr = HttpClientUtils.httpGet(getTokenUrl);//获取json格式的字符串
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);//转换成对象，里面保存了opeanId，和access_token
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        Wxuser wxuser = wxuserMapper.loadByopenId(openId);//获取数据库中的wxuser
        if(wxuser != null && wxuser.getUserId() != null) {
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId()); //查询logininfo中的对象loginfo

            //登录成功之后的业务处理,jwt存储方式
            Map<String, Object> map = loginSuccessHandler(logininfo);
            return AjaxResult.me().setResultObj(map);
            /*//保存redis，设置过期时间
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(
                    token,
                    logininfo,
                    30,
                    TimeUnit.MINUTES
            );
            HashMap<String, Object> map = new HashMap<>();
            logininfo.setPassword(null);
            logininfo.setSalt(null);
            map.put("token",token);
            map.put("logininfo",logininfo);
             return AjaxResult.me().setResultObj(map);
         } else {
            binderUrl ="?accessToken="+accessToken+"&openId="+openId;
            return AjaxResult.me().setSuccess(false).setResultObj(binderUrl);
        }*/
        }
        return null;
    }

    /**
     * 微信登录绑定用户
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> binder(wechatBinderDto dto) {
        //非空判断
        if (StringUtils.isEmpty(dto.getPhone())
            ||StringUtils.isEmpty(dto.getAccessToken())
            ||StringUtils.isEmpty(dto.getType())
            ||StringUtils.isEmpty(dto.getVerifyCode())
            ||StringUtils.isEmpty(dto.getOpenId())){
            throw new BusinessException("参数不能为空");
        }
//短信验证码校验
        String smsCodeKey = BaseConstants.VerifyCodeConstants.BUSINESS_BINDER_PREFIX + dto.getPhone();//redis的key
        Object smsCodeValueTmp = redisTemplate.opsForValue().get(smsCodeKey);//从redis中查找值
        if(smsCodeValueTmp == null){
            throw new BusinessException("验证码已失效请重写发送");
        }
        String smsCodeValue = smsCodeValueTmp.toString().split(":")[0];
        if (!smsCodeValue.equalsIgnoreCase(dto.getVerifyCode())){
            throw new BusinessException("请输入正确的验证码");
        }
        User user = userMapper.loadByPhone(dto.getPhone());
        Logininfo logininfo = null;
        if (user == null){
           // - 不存在，生成user + logininfo
            user = initUser(dto.getPhone());
            logininfo  =user2logininfo(user);
            logininfoMapper.save(logininfo);//返回自增id
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        } else {
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }
        String wxUserUrl = BaseConstants.WechatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN",dto.getAccessToken())
                .replace("OPENID", dto.getOpenId());//第二次后端请求，请求wx后台
        String wxUserJsonStr = HttpClientUtils.httpGet(wxUserUrl);//发送请求微信数据json格式字符串
        Wxuser wxuser = JSONObject.parseObject(wxUserJsonStr, Wxuser.class);
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);

        //登录成功之后的业务处理,jwt存储方式
        return loginSuccessHandler(logininfo);


        /*String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfo,
                30,
                TimeUnit.MINUTES
        );
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;*/
    }

    private Logininfo user2logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//一定要设置
        return logininfo;
    }

    private User initUser(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5("1" + salt);
        SmsUtils.sendMsg(phone,"您的默认密码是：1,如有需要请手动修改");
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        return user;
    }
}
